﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Data ;
using ZhiAo.CoreLibrary;
using ZhiAo.WebLib.Data;

namespace ZhiAo.CommonLibrary
{
    public static class DropdownListHelper
    {
        public static void BindQueryData(this DropDownList cboList, string sql, bool addAll)
        {
            DataTable data = null;
            if (sql.ToLower().Contains("select"))
            {
                data = DBHelper.GetDataTable(sql);

            }
            else
            {
                data = GetDataByFixed(sql);
            }

            cboList.DataValueField = data.Columns[0].ColumnName;
            cboList.DataTextField = data.Columns[1].ColumnName;
            cboList.DataSource = data;
            cboList.DataBind();
            if (addAll) cboList.Items.Insert(0, new ListItem("-全部-", ""));
        }

        public static void BindQueryData(this DropDownList cboList, string sql)
        {
            BindQueryData(cboList, sql, true);
        }

        private static DataTable GetDataByFixed(string fixedString)
        {
            DataTable table = new DataTable();
            table.Columns.Add("CODE");
            table.Columns.Add("NAME");
            string[] array = fixedString.Split(',');
            foreach (string item in array)
            {
                string[] itemArray = item.Split('|');
                string code = itemArray[0].Trim();
                string name = "";
                if (itemArray.Length == 0)
                {
                    name = code;
                }
                else
                {
                    name = itemArray[1].Trim();
                }

                table.Rows.Add(new object[] { code, name });
            }

            return table;
        }
    }
}
